import {Component, Input, OnInit, TemplateRef} from "@angular/core";
import {SmartTableData} from "../../@core/data/smart-table";
import {NbDialogService} from "@nebular/theme";
import {BillExtaService} from "../../energy/api/api/billExta.service";
import {AdminService} from "../../AdminService";
import {CustomTimeRender} from "../../utils/CustomTimeRender";
import {DataDataSource} from "../cost-list/cost-list.component";
import {RateBindComponent} from "../cost-list/rate-bind.component";
import {CommonFormDialog} from "../../utils/CommonFormDialog";
import {BaseRequest} from "../../utils/BaseRequest";

@Component({
  selector: 'unit-rate-component',
  templateUrl: `./unit-rate.component.html`,
  styles: [
    `
    button{
        margin: 5px;
    }
    `
  ]
})
export class UnitRateComponent implements OnInit {
  @Input("unitId") unitId: number;
  @Input("unitName") unitName:string;
  source: DataDataSource;
  settings = {
    pager: {
      display: true,
      perPage: 20,
    },
    hideSubHeader: true,
    actions: {
      add: false,
      edit: false,
      columnTitle: '操作',
      position: 'right',
    },
    delete: {
      deleteButtonContent: `<i class="nb-trash"></i>`,
      confirmDelete: true,
    },
    columns: {
      name: {
        title: '名称',
        type: 'string',
      },
      startTime: {
        title: '起始时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      endTime: {
        title: '结束时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      rate: {
        title: '费率',
        type: 'string',
      },
      extInfo: {
        title: '备注',
        type: 'string',
      }
    },
  };
  constructor(private service: SmartTableData, private dialogService: NbDialogService, private api: BillExtaService, private admin: AdminService) {

  }

  ngOnInit(): void {
    this.source = new DataDataSource(this.api, null, this.unitId);
  }

  filter() {

  }

  openAddPrompt() {
    this.dialogService.open(RateBindComponent,{
      context:{
        data:{unitId:this.unitId,unitName:this.unitName},
      }
    }).onClose.subscribe(result=>{
      this.source.refresh();
    });
  }

  onDeleteConfirm(event){
    if (window.confirm('是否要解除绑定?')) {
      const rateId = event.data['id'];
      this.api.postBindECARate(new BaseRequest({
        operation: 1,
        unitId: this.unitId,
        rateId: rateId
      })).subscribe(res => {
        if (res.success) {
          this.source.refresh();
          event.confirm.resolve();
        } else {
          event.confirm.reject();
        }
      })
    }else{
      event.confirm.reject();
    }
  }
}

